﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Siparisler
{
    public partial class Maliyet : XForm
    {
        public Maliyet()
        {
            InitializeComponent();

            TAM.MaliyetTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetTableAdapter();
            TAM.MaliyetLinesTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetLinesTableAdapter();
            TAM.MaliyetLinesAccsTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetLinesAccsTableAdapter();
            TAM.MaliyetLinesCmtTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetLinesCmtTableAdapter();
            TAM.MaliyetLinesExtrasTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetLinesExtrasTableAdapter();
            TAM.MaliyetLinesGrnTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetLinesGrnTableAdapter();
            TAM.MaliyetLinesKumasTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.MaliyetLinesKumasTableAdapter();
        }

        int pos1, pos2, pos3;
        BindingSource bs, bsLines, bsCmt, bsAccs, bsExtras, bsGrn, bsKumas;
        private void Maliyet_Load(object sender, EventArgs e)
        {
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);

            ds.MaliyetLines.Columns.Add("FobShirtPrice1", typeof(decimal));
            ds.MaliyetLines.Columns.Add("FobShirtPrice2", typeof(decimal));

            Exp(true);

            bs = new BindingSource(ds, "Maliyet");
            bsLines = new BindingSource(bs, "FK_MaliyetLines_Maliyet_MaliyetId");
            bsCmt = new BindingSource(bsLines, "FK_MaliyetLinesCmt_MaliyetLines_MaliyetLinesId");
            bsAccs = new BindingSource(bsLines, "FK_MaliyetLinesAccs_MaliyetLines_MaliyetLinesId");
            bsExtras = new BindingSource(bsLines, "FK_MaliyetLinesExtras_MaliyetLines_MaliyetLinesId");
            bsGrn = new BindingSource(bsLines, "FK_MaliyetLinesGrn_MaliyetLines_MaliyetLinesId");
            bsKumas = new BindingSource(bsLines, "FK_MaliyetLinesKumas_MaliyetLines_MaliyetLinesId");

            AddBsToList(bs, bsLines, bsCmt, bsAccs, bsCmt, bsExtras, bsGrn, bsKumas);

            //GridManager.Initialize(Enums.FormId.Maliyet,
            //    new GridView[] { gv1 },
            //    new BindingSource[] { bsLines });

            InitGridView(gv1, bsLines);

            gv1.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;


            Gizle3();

            chkGoster.CheckedChanged += new EventHandler(chkGoster_CheckedChanged);
            chkGoster.Checked = true;
            chkGoster.Visible = false;

            int cnt = 0;
            gv1.Images = bgvIcons;
            //string[] parts = "SALES ORDER DETAILS;FABRIC DETAILS;INTERNAL DATA;ÜRETİM OLACAK KUMAŞ DETAYLARI;CALCULATION DATA;MARGINS;PRICES WITH DIFFERENT TERMS;QUOTATION".Split(';');
            string[] parts = "SALES ORDER DETAILS;FABRIC DETAILS;ÜRETİM OLACAK KUMAŞ DETAYLARI;CALCULATION DATA;MARGINS;PRICES WITH DIFFERENT TERMS;QUOTATION".Split(';');
            //string[] starts = "MaliyetLinesId;OrgVendor;NetBirimMetraj;ProductionVendorId;KumasMaliyeti;KarbelMarginSabit;FobShirtPrice;GivenPrice;".Split(';');
            string[] starts = "MaliyetLinesId;DesNo;ProductionVendorId;KumasMaliyeti;KarbelMarginSabit;FobShirtPrice;GivenPrice;".Split(';');
            for (int i = 0; i < parts.Length; i++)
            {
                GridBand gb = new DevExpress.XtraGrid.Views.BandedGrid.GridBand();
                gb.Caption = "<b>" + parts[i] + "</b>";
                gb.ImageIndex = i % 6;
                gb.Name = "gb" + gb.ImageIndex.ToString();
                //TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gb.OptionsBand.AllowHotTrack = true;
                gv1.Bands.Add(gb);

                for (int i2 = cnt; i2 < gv1.Columns.Count; i2++)
                {
                    if (gv1.Columns[cnt].FieldName == starts[i + 1] && cnt > 0)
                        break;

                    gv1.Bands[i].Columns.Add(gv1.Columns[cnt]);
                    cnt++;
                }
            }
            gv1.OptionsView.AllowHtmlDrawHeaders = true;
            //gv1.Columns["Scan"].ColVIndex = gv1.Columns["ProductId"].ColVIndex;


            //((RepositoryItemLookUpEdit)gv1.Columns["UreticiId"].ColumnEdit).TextEditStyle = TextEditStyles.Standard;

            gv1.FocusedColumnChanged += new DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventHandler(gv1_FocusedColumnChanged);

            //buttonEdit1.ButtonClick += new ButtonPressedEventHandler(buttonEdit1_ButtonClick);
            //buttonEdit1.EditValueChanged += new EventHandler(buttonEdit1_EditValueChanged);

            btnSave.Click += new EventHandler(btnSave_Click);

            gleBrand.Properties.Assign(RI(Rp.Brand));
            gleCurrency.Properties.Assign(RI(Rp.Currency));
            gleCurrency.EditValueChanged += new EventHandler(gleCurrency_EditValueChanged);
            glePriceTerm.Properties.Assign(RI(Rp.PriceTerm));
            gleAtelye.Properties.Assign(RI(Rp.Atelye));
            gleSezon.Properties.Assign(RI(Rp.Sezon));

            gleBrand.DataBindings.Add("EditValue", bs, "BrandId");
            gleCurrency.DataBindings.Add("EditValue", bs, "CurrencyId");
            glePriceTerm.DataBindings.Add("EditValue", bs, "PriceTermId");
            teOrderRef.DataBindings.Add("EditValue", bs, "OrderRef");
            gleAtelye.DataBindings.Add("EditValue", bs, "AtelyeId");
            gleSezon.DataBindings.Add("EditValue", bs, "SezonId");
            deTarih.DataBindings.Add("EditValue", bs, "Tarih");
            lblVer.DataBindings.Add("Text", bs, "Versiyon");

            lblVer.ToolTip = "Versiyon";
            gleBrand.Properties.ReadOnly = gleCurrency.Properties.ReadOnly = glePriceTerm.Properties.ReadOnly = teOrderRef.Properties.ReadOnly = gleAtelye.Properties.ReadOnly = gleSezon.Properties.ReadOnly = deTarih.Properties.ReadOnly = true;

            foreach (string str in "GumrukPct;KarbelMarginPct;CommPct;Surcharge_Discount;KumasaKonanMarj".Split(';'))
            {
                gv1.Columns[str].Caption = gv1.Columns[str].Caption.Replace("Pct", "%").Replace("_", "/");

                gv1.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                ((RepositoryItemTextEdit)gv1.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                ((RepositoryItemTextEdit)gv1.Columns[str].ColumnEdit).DisplayFormat.Format = new FormatYuzde(); //"{0:p0}";
            }

            gv1.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gv1_CellValueChanged);
            gv1.RowCellStyle += new RowCellStyleEventHandler(gv1_RowCellStyle);

            colors = new Color[]{
                Color.FromArgb(220, 232, 162),
                Color.FromArgb(238, 243, 213),
                Color.FromArgb(234, 247, 249),
                Color.FromArgb(219, 238, 243),

                Color.FromArgb(238, 248, 249),
                Color.FromArgb(229, 224, 236),
                Color.FromArgb(238, 195, 217),

                Color.FromArgb(229, 224, 236)
            };

            gv1.OptionsView.EnableAppearanceEvenRow = false;

            //gv1.Columns["Tl"].ToolTip = "FabricPurchasePrice in TL";
            //gv1.Columns["Usd"].ToolTip = "FabricPurchasePrice in USD";
            //gv1.Columns["Eur"].ToolTip = "FabricPurchasePrice in EUR";

            gleBrand.BorderStyle = gleSezon.BorderStyle = gleCurrency.BorderStyle = glePriceTerm.BorderStyle = teOrderRef.BorderStyle = gleAtelye.BorderStyle = BorderStyles.Default;  //properties.assign dan sonra kullanılması zorunlu yoksa borderless görünüyor!

            gv1.Columns["ToplamGarniMaliyeti"].AutoFillDown = true;

            gv1.Images = bgvIcons;
            gv1.Columns["ConvertedFabricPrice"].ImageIndex =
            gv1.Columns["ToplamGarniMaliyeti"].ImageIndex =
            gv1.Columns["Accs"].ImageIndex =
            gv1.Columns["Cmt"].ImageIndex =
            gv1.Columns["Extras"].ImageIndex = 6;
            gv1.Columns["Extras"].ToolTip = "Nakış, Baskı, Süs Dikiş vb. Dış İşlemler";

            teQuickJump.EditValueChanged += new EventHandler(textEdit1_EditValueChanged);
            teQuickJump.ToolTip = "Buraya adını yazacağınız sütuna kolayca ulaşabilirsiniz.";

            //buttonEdit1.Properties.ReadOnly = true;
            //buttonEdit1.PerformClick(buttonEdit1.Properties.Buttons[0]);
            btnNew.Click += new EventHandler(btnNew_Click);
            btnOpen.Click += new EventHandler(btnOpen_Click);

            btnSave.Enabled = btnJustSave.Enabled = lblQuickJump.Visible = teQuickJump.Visible = false;

            gv1.Columns["MaliyetId"].Visible = gv1.Columns["MaliyetLinesId"].Visible = gv1.Columns["Notes2"].Visible = false;
            this.FormClosing += new FormClosingEventHandler(Maliyet_FormClosing);

            gv1.Columns["Cmt"].Caption = "Model Farkı";
            gv1.Columns["Extras"].Caption = "Other Extras";
            gv1.Columns["Accs"].Caption = "Other Accs";
            //gv1.Columns["Cmt"].Caption = "Model Farkı";

            btnJustSave.Click += new EventHandler(btnJustSave_Click);
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);

            chkHide.CheckedChanged += new EventHandler(chkHide_CheckedChanged);
        }

        //int cols;
        Dictionary<string, int> colPos = new Dictionary<string, int>();
        void chkHide_CheckedChanged(object sender, EventArgs e)
        {
            if (chkHide.Checked)
            {
                //kaydet+gizle
                //cols = 0;
                colPos.Clear();
                for (int i = gv1.Columns.Count - 1; i > 0; i--)
                {
                    colPos[gv1.Columns[i].FieldName] = gv1.Columns[i].VisibleIndex;

                    bool empty = true;
                    for (int j = 0; j < ds.MaliyetLines.Rows.Count; j++)
                        if (ds.MaliyetLines[j][gv1.Columns[i].FieldName] != null)
                            if (ds.MaliyetLines[j][gv1.Columns[i].FieldName] != DBNull.Value)
                            {
                                empty = false;
                                break;
                            }

                    if (empty)
                        gv1.Columns[i].Visible = false;
                    //cols++;
                }
            }
            else
            {

                foreach (var pair in colPos)
                    gv1.Columns[pair.Key].VisibleIndex = pair.Value;

            }
        }

        void btnJustSave_Click(object sender, EventArgs e)
        {
            if (MaliyetId > 0)
                try
                {
                    Exp(false);
                    Save();
                }
                finally
                {
                    Exp(true);
                }
        }

        private void Gizle3()
        {
            pos1 = gv1.Columns["Descr"].VisibleIndex;
            pos2 = gv1.Columns["Qty"].VisibleIndex;
            pos3 = gv1.Columns["Notes1"].VisibleIndex;
            gv1.Columns["Descr"].VisibleIndex = gv1.Columns["Qty"].VisibleIndex = gv1.Columns["Notes1"].VisibleIndex = -1;
        }

        void chkGoster_CheckedChanged(object sender, EventArgs e)
        {
            if (chkGoster.Checked)
            {
                gv1.Columns["Notes1"].VisibleIndex = pos3;
                gv1.Columns["Qty"].VisibleIndex = pos2;
                gv1.Columns["Descr"].VisibleIndex = pos1;
            }
            else
                Gizle3();
        }


        void Maliyet_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (ds.MaliyetLines.GetChanges() != null)
            //    if (XtraMessageBox.Show("Emin misiniz?", "Confirm", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
            //        e.Cancel = true;
        }

        //void btnYukselt_Click(object sender, EventArgs e)
        //{
        //    if (XtraMessageBox.Show("Emin misiniz?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
        //        GetDetails("Maliyet", "MaliyetVerYukselt", MaliyetId);
        //}

        void btnOpen_Click(object sender, EventArgs e)
        {
            using (MaliyetList ml = new MaliyetList())
                if (ml.ShowDialog() == DialogResult.OK)
                    if (ml.MaliyetId > 0)
                    {
                        Arrange4Visibility(ml.MaliyetId);
                    }
        }

        void btnNew_Click(object sender, EventArgs e)
        {
            using (MaliyetYeni ml = new MaliyetYeni())
                if (ml.ShowDialog() == DialogResult.OK)
                {
                    Arrange4Visibility(ml.MaliyetId);
                }
        }

        private void Arrange4Visibility(int _MaliyetId)
        {
            MaliyetId = _MaliyetId;
            MaliyetChanged();

            btnSave.Enabled = btnJustSave.Enabled = /*lblQuickJump.Visible = teQuickJump.Visible =*/ true;

            int pos = gv1.Columns["GivenPrice"].VisibleIndex - 1;
            gv1.Columns["FobShirtPrice"].VisibleIndex = glePriceTerm.Text == "FOB" ? pos : -1;
            gv1.Columns["CifPrice"].VisibleIndex = glePriceTerm.Text == "CIF" ? pos : -1;
            gv1.Columns["CifTransport"].VisibleIndex = glePriceTerm.Text == "CIF" ? pos : -1;
            gv1.Columns["LdpPriceBoat"].VisibleIndex = glePriceTerm.Text == "LDP by BOAT" ? pos : -1;
            gv1.Columns["LdpPriceAir"].VisibleIndex = glePriceTerm.Text == "LDP by AIR" ? pos : -1;
        }

        void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (teQuickJump.Text != string.Empty)
                foreach (BandedGridColumn c in gv1.Columns)
                    if (c.FieldName.ToLower().StartsWith(teQuickJump.Text.ToLower()))
                    {
                        gv1.MakeColumnVisible(c);
                        break;
                    }
        }

        Color[] colors;
        void gv1_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "FobShirtPrice" && glePriceTerm.Text == "FOB" ||
                e.Column.FieldName == "CifPrice" && glePriceTerm.Text == "CIF" ||
                e.Column.FieldName == "LdpPriceBoat" && glePriceTerm.Text == "LDP by BOAT" ||
                e.Column.FieldName == "LdpPriceAir" && glePriceTerm.Text == "LDP by AIR")
                e.Appearance.BackColor = Color.YellowGreen;

            else if (!gv1.OptionsView.AllowCellMerge)
                if (e.RowHandle % 2 == 0 && e.Appearance.BackColor == Color.White)
                    if (((BandedGridColumn)e.Column).OwnerBand != null)
                        e.Appearance.BackColor = colors[((BandedGridColumn)e.Column).OwnerBand.Index];

            if (e.Column.FieldName == "GivenPrice")
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        bool suspend = false;
        void gv1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (!suspend)
                try
                {
                    suspend = true;
                    if (e.Column.FieldName.EndsWith("Pct"))
                        gv1.SetRowCellValue(e.RowHandle, e.Column.FieldName.Replace("Pct", "Sabit"), DBNull.Value);
                    else if (e.Column.FieldName.EndsWith("Sabit"))
                        gv1.SetRowCellValue(e.RowHandle, e.Column.FieldName.Replace("Sabit", "Pct"), DBNull.Value);
                }
                finally
                {
                    suspend = false;
                }
        }


        string[] dvzArr = "; €; $; £; TL".Split(';');
        void gleCurrency_EditValueChanged(object sender, EventArgs e)
        {
            if (ds.Maliyet.Rows.Count > 0)
            {
                //if (!ds.Maliyet[0].IsCurrencyIdNull())
                dvz = dvzArr[ds.Maliyet[0].CurrencyId];     //1	EUR, 2	USD, 3	GBP

                foreach (string str in "ConvertedFabricPrice;Nakliye;KumasMaliyeti;BasicCmt;Cmt;Washing_GDye;Extras;BasicAccs;Accs;ToplamGarniMaliyeti;TotalCost;FobShirtPrice;CifTransport;CifPrice;LdpPriceBoat;LdpPriceAir;GivenPrice".Split(';'))
                {
                    gv1.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                    ((RepositoryItemTextEdit)gv1.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    ((RepositoryItemTextEdit)gv1.Columns[str].ColumnEdit).DisplayFormat.FormatString = "#,##0.00" + dvz;
                }
                foreach (string str in "GumrukSabit;KarbelMarginSabit;CommSabit".Split(';'))
                {
                    gv1.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                    ((RepositoryItemTextEdit)gv1.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    ((RepositoryItemTextEdit)gv1.Columns[str].ColumnEdit).DisplayFormat.FormatString = "#,##0.##" + dvz;
                }
            }
        }


        //http://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraBarsAlerterAlertControltopic
        void Exp(bool flag)
        {
            if (flag)
            {
                ds.MaliyetLinesKumas.Columns["KumasIhtiyaci"].Expression = "Parent(FK_MaliyetLinesKumas_MaliyetLines_MaliyetLinesId).Qty * NetBirimMetraj";
                ds.MaliyetLinesKumas.Columns["ConvertedFabricPrice"].Expression = "(ISNULL(Tl,0)+ISNULL(Eur,0)*" + katsayi(1) + "+ISNULL(Usd,0)*" + katsayi(2) + ")/" + katsayi(0);

                ds.MaliyetLines.Columns["ConvertedFabricPrice"].Expression = "SUM(Child(FK_MaliyetLinesKumas_MaliyetLines_MaliyetLinesId).ConvertedFabricPrice)";
                ds.MaliyetLines.Columns["KumasMaliyeti"].Expression = "IIF(GumrukPct>0, ConvertedFabricPrice*(1+GumrukPct/100.0), ConvertedFabricPrice+ISNULL(GumrukSabit,0))+ISNULL(Nakliye,0)";
                //ds.MaliyetLines.Columns["Cmt"].Expression = "SUM(Child(FK_MaliyetLinesCmt_MaliyetLines_MaliyetLinesId).TlFasonUcreti)/" + katsayi(0);
                ds.MaliyetLines.Columns["Cmt"].Expression = "SUM(Child(FK_MaliyetLinesCmt_MaliyetLines_MaliyetLinesId).ExtraMaliyet)";

                ds.MaliyetLines.Columns["Extras"].Expression = "(ISNULL(SUM(Child(FK_MaliyetLinesExtras_MaliyetLines_MaliyetLinesId).Tl),0)" +
                    "+ISNULL(SUM(Child(FK_MaliyetLinesExtras_MaliyetLines_MaliyetLinesId).Eur),0)*" + katsayi(1) +
                    "+ISNULL(SUM(Child(FK_MaliyetLinesExtras_MaliyetLines_MaliyetLinesId).Usd),0)*" + katsayi(2) +
                    "+ISNULL(SUM(Child(FK_MaliyetLinesExtras_MaliyetLines_MaliyetLinesId).Gbp),0)*" + katsayi(3) + ")/" + katsayi(0);
                ds.MaliyetLines.Columns["Accs"].Expression = "(ISNULL(SUM(Child(FK_MaliyetLinesAccs_MaliyetLines_MaliyetLinesId).Tl),0)" +
                    "+ISNULL(SUM(Child(FK_MaliyetLinesAccs_MaliyetLines_MaliyetLinesId).Eur),0)*" + katsayi(1) +
                    "+ISNULL(SUM(Child(FK_MaliyetLinesAccs_MaliyetLines_MaliyetLinesId).Usd),0)*" + katsayi(2) +
                    "+ISNULL(SUM(Child(FK_MaliyetLinesAccs_MaliyetLines_MaliyetLinesId).Gbp),0)*" + katsayi(3) + ")/" + katsayi(0);
                ds.MaliyetLines.Columns["TotalCost"].Expression = "(KumasMaliyeti*(1+ISNULL(KumasaKonanMarj,0))*HesaplananBirimMetraj)+ ISNULL(ToplamGarniMaliyeti,0)+ ISNULL(BasicCmt,0)+ISNULL(Cmt,0)+ISNULL(Washing_GDye,0)+ISNULL(Extras,0)+ISNULL(BasicAccs,0)+ISNULL(Accs,0)";

                ds.MaliyetLines.Columns["FobShirtPrice1"].Expression = "IIF(KarbelMarginPct>0, TotalCost*(1+KarbelMarginPct/100.0), TotalCost+ISNULL(KarbelMarginSabit,0))";
                ds.MaliyetLines.Columns["FobShirtPrice2"].Expression = "IIF(CommPct>0, FobShirtPrice1*(1+CommPct/100.0), FobShirtPrice1+ISNULL(CommSabit,0))";
                ds.MaliyetLines.Columns["FobShirtPrice"].Expression = "FobShirtPrice2*(1-ISNULL(Surcharge_Discount/100.0,0))";

                ds.MaliyetLines.Columns["CifPrice"].Expression = "FobShirtPrice+ISNULL(CifTransport,0)";
                ds.MaliyetLines.Columns["LdpPriceBoat"].Expression = "IIF(Parent(FK_MaliyetLines_Maliyet_MaliyetId).BrandId=79, FobShirtPrice + 3, FobShirtPrice*1.2 + 1)";
                ds.MaliyetLines.Columns["LdpPriceAir"].Expression = "IIF(Parent(FK_MaliyetLines_Maliyet_MaliyetId).BrandId=79, FobShirtPrice + 4, FobShirtPrice*1.2 + 2.25)";
                //79: PETER MILLAR

                ds.MaliyetLinesGrn.Columns["KumasIhtiyaci"].Expression = "Parent(FK_MaliyetLinesGrn_MaliyetLines_MaliyetLinesId).Qty * NetBirimMetraj";
                ds.MaliyetLinesGrn.Columns["ConvertedFabricPrice"].Expression = "(ISNULL(Tl,0)+ISNULL(Eur,0)*" + katsayi(1) + "+ISNULL(Usd,0)*" + katsayi(2) + ")/" + katsayi(0);
                ds.MaliyetLinesGrn.Columns["KumasMaliyeti"].Expression = "IIF(GumrukPct>0, ConvertedFabricPrice*(1+GumrukPct/100.0), ConvertedFabricPrice+ISNULL(GumrukSabit,0))+ISNULL(Nakliye,0)";
                ds.MaliyetLinesGrn.Columns["GarniMaliyeti"].Expression = "(KumasMaliyeti*HesaplananBirimMetraj)";

                ds.MaliyetLines.Columns["ToplamGarniMaliyeti"].Expression = "SUM(Child(FK_MaliyetLinesGrn_MaliyetLines_MaliyetLinesId).GarniMaliyeti)";

            }
            else
                ds.MaliyetLinesKumas.Columns["KumasIhtiyaci"].Expression =
                ds.MaliyetLinesKumas.Columns["ConvertedFabricPrice"].Expression =
                ds.MaliyetLines.Columns["ConvertedFabricPrice"].Expression =
                ds.MaliyetLines.Columns["KumasMaliyeti"].Expression =
                ds.MaliyetLines.Columns["Cmt"].Expression =
                ds.MaliyetLines.Columns["Extras"].Expression =
                ds.MaliyetLines.Columns["Accs"].Expression =
                ds.MaliyetLines.Columns["TotalCost"].Expression =
                ds.MaliyetLines.Columns["FobShirtPrice1"].Expression =
                ds.MaliyetLines.Columns["FobShirtPrice2"].Expression =
                ds.MaliyetLines.Columns["FobShirtPrice"].Expression =
                ds.MaliyetLines.Columns["CifPrice"].Expression =
                ds.MaliyetLines.Columns["LdpPriceBoat"].Expression =
                ds.MaliyetLines.Columns["LdpPriceAir"].Expression =
                ds.MaliyetLinesGrn.Columns["KumasIhtiyaci"].Expression =
                ds.MaliyetLinesGrn.Columns["ConvertedFabricPrice"].Expression =
                ds.MaliyetLinesGrn.Columns["KumasMaliyeti"].Expression =
                ds.MaliyetLinesGrn.Columns["GarniMaliyeti"].Expression =
                ds.MaliyetLines.Columns["ToplamGarniMaliyeti"].Expression = null;
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (MaliyetId > 0)
                using (MaliyetRvs mr = new MaliyetRvs(MaliyetId))
                    if (mr.ShowDialog() == DialogResult.OK)
                        if (mr.Revision > 0)
                            try
                            {
                                Exp(false);
                                ds.Maliyet[0].Versiyon = mr.Revision;
                                Save();
                            }
                            finally
                            {
                                Exp(true);
                            }
        }


        string katsayi(int i)
        {
            IFormatProvider iFormatProvider = System.Globalization.CultureInfo.InvariantCulture;
            //new System.Globalization.CultureInfo("es-ES");
            //string s2 = string.Format(iFormatProvider, "{0:#,##0.000}", val)
            //Note that the , and . are using a 'standard' en-US style, but .ToString() and string.Format() with a format provider does the right thing.

            return curr[i].ToString("#,##0.000", iFormatProvider);
        }

        string dvz = string.Empty;
        decimal[] curr = new decimal[5];


        int MaliyetId;
        private void MaliyetChanged()
        {
            ds.Clear();
            Exp(false);
            GetDetails("Maliyet;MaliyetLines;MaliyetLinesAccs;MaliyetLinesCmt;MaliyetLinesExtras;MaliyetLinesGrn;MaliyetLinesKumas", "GetMaliyet", MaliyetId);

            if (ds.Maliyet.Rows.Count > 0)
            {
                //if (!ds.Maliyet[0].IsEurNull())
                curr[1] = ds.Maliyet[0].Eur;
                curr[2] = ds.Maliyet[0].Usd;
                curr[3] = ds.Maliyet[0].Gbp;
                curr[4] = 1;

                curr[0] = curr[ds.Maliyet[0].CurrencyId];   //hedef currency

                if (!ds.Maliyet[0].IsScenarioIdNull())
                    if (ds.Maliyet[0].ScenarioId == 1)
                    {
                        gv1.Columns["KumasaKonanMarj"].Visible = false;
                        gv1.Columns["KarbelMarginPct"].VisibleIndex = gv1.Columns["TotalCost"].VisibleIndex + 1;
                        gv1.Columns["KarbelMarginSabit"].VisibleIndex = gv1.Columns["TotalCost"].VisibleIndex + 1;
                    }
                    else
                    {
                        gv1.Columns["KumasaKonanMarj"].VisibleIndex = gv1.Columns["KumasMaliyeti"].VisibleIndex + 1;
                        gv1.Columns["KarbelMarginPct"].Visible =
                        gv1.Columns["KarbelMarginSabit"].Visible = false;
                    }

                pnlMaliyet.Visible = true;
            }

            Exp(true);
            gv1.BestFitColumns();
        }

        void gv1_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        {
            bool showgrid = true;
            switch (gv1.FocusedColumn.FieldName)
            {
                case "Accs":
                    InitGridView(gv2, bsAccs);
                    foreach (string str in "MaliyetLinesAccsId;MaliyetLinesId;UserId".Split(';'))
                        gv2.Columns[str].Visible = false;

                    gv2.AddSummary("Tl", "Usd", "Eur", "Gbp");
                    gv2.SetViewCaption("Accs");
                    break;

                case "Extras":
                    InitGridView(gv2, bsExtras);

                    foreach (string str in "MaliyetLinesExtrasId;MaliyetLinesId;UserId".Split(';'))
                        gv2.Columns[str].Visible = false;

                    gv2.AddSummary("Tl", "Usd", "Eur", "Gbp");
                    gv2.SetViewCaption("Extras  (Nakış, Baskı, Süs Dikiş vb. Dış İşlemler)");
                    break;

                case "Cmt":
                    InitGridView(gv2, bsCmt);
                    foreach (string str in "MaliyetLinesCmtId;MaliyetLinesId;UserId".Split(';'))
                        gv2.Columns[str].Visible = false;

                    gv2.AddSummary("TlFasonUcreti", "ExtraMaliyet");
                    foreach (string str in "ExtraMaliyet".Split(';'))
                    {
                        gv2.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                        ((RepositoryItemTextEdit)gv2.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        ((RepositoryItemTextEdit)gv2.Columns[str].ColumnEdit).DisplayFormat.FormatString = "#,##0.00" + dvz;
                    }

                    gv2.SetViewCaption("Cmt");
                    break;

                case "ToplamGarniMaliyeti":
                    InitGridView(gv2, bsGrn);
                    foreach (string str in "MaliyetLinesGrnId;MaliyetLinesId;KumasListeFiyati;DovizCinsiId;FabricNote;ProductionVendorId;Width;TeslimSekliAId;ConvertedFabricPrice;GumrukSabit;GumrukPct;Nakliye;KumasMaliyeti;TS;ModifiedOn".Split(';'))
                        gv2.Columns[str].Visible = false;

                    gv2.AddSummary("Tl", "Usd", "Eur");
                    foreach (string str in "ConvertedFabricPrice;Nakliye;KumasMaliyeti;GarniMaliyeti".Split(';'))
                    {
                        gv2.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                        ((RepositoryItemTextEdit)gv2.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        ((RepositoryItemTextEdit)gv2.Columns[str].ColumnEdit).DisplayFormat.FormatString = "#,##0.00" + dvz;
                    }
                    //foreach (string Message in "GumrukSabit".Split(';'))
                    //{
                    //    gv2.Columns[Message].ColumnEdit = new RepositoryItemTextEdit();
                    //    ((RepositoryItemTextEdit)gv2.Columns[Message].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    //    ((RepositoryItemTextEdit)gv2.Columns[Message].ColumnEdit).DisplayFormat.FormatString = "#,###.##" + dvz;
                    //}
                    gv2.SetViewCaption("Garni");
                    break;

                //default:
                case "ConvertedFabricPrice":
                    InitGridView(gv2, bsKumas);
                    foreach (string str in "MaliyetLinesKumasId;MaliyetLinesId".Split(';'))
                        gv2.Columns[str].Visible = false;

                    gv2.AddSummary("Tl", "Usd", "Eur");
                    foreach (string str in "ConvertedFabricPrice".Split(';'))
                    {
                        gv2.Columns[str].ColumnEdit = new RepositoryItemTextEdit();
                        ((RepositoryItemTextEdit)gv2.Columns[str].ColumnEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        ((RepositoryItemTextEdit)gv2.Columns[str].ColumnEdit).DisplayFormat.FormatString = "#,##0.00" + dvz;
                    }
                    gv2.FormatAsNumber(2, "KumasIhtiyaci");
                    gv2.SetViewCaption("AnaBeden");
                    break;

                default:
                    showgrid = false;
                    break;

            }
            gc2.Visible = showgrid;

            gv2.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gv2.BestFitColumns();

            ExpandCollapse(splitContainerControl1, showgrid ? AcKapa.Expand : AcKapa.Collapse);
            //ExpandCollapse(splitContainerControl1, gv2.Columns.Count == 0 ? AcKapa.Collapse : AcKapa.Expand);
        }
    }
}